import { _decorator, Component, Node, sp, tween, Vec2, Vec3 } from 'cc';
import { UICtrl } from './UICtrl';
import { EventMgr } from './EventMgr';
const { ccclass, property } = _decorator;

@ccclass('RoleCtrl')
export class RoleCtrl extends UICtrl {
    @property(sp.Skeleton)
    public playerImg:sp.Skeleton;
    public movePosArr: Vec3[] = [];
    public isMoveOver:boolean = false;
    public moveDir:string;
    public overFun:Function;
    public skinName:string;
    public type:string;
    
    public moveCharacter(index) {
        if (index == 0){
            this.playerImg.animation = this.skinName;
            this.isMoveOver = false;
        }
        if (index >= this.movePosArr.length){
            this.moveOver();
            this.isMoveOver = true;
            return;
        }
        let pos = index == 0 ? this.node.position:this.movePosArr[index-1]
        let lastPos = new Vec2(pos.x,pos.y)
        let nowPos = new Vec2(this.movePosArr[index].x,this.movePosArr[index].y)
        let distance = Vec2.distance(lastPos, nowPos);

        let scale = this.playerImg.node.getScale();
        if (nowPos.x!=lastPos.x) {
            scale.x = Math.abs(scale.x) * nowPos.x>lastPos.x?1:-1;
        }
        this.playerImg.node.setScale(scale);
        let duration = distance / 300; // 计算移动所需的时间 (250/s)
        tween(this.node)
            .to(duration, { position: this.movePosArr[index] })
            .call(() => {
                this.moveCharacter(index+1);
            }).start();
        if (this.type == "boss" && this.moveDir == "forward" && index == this.movePosArr.length-2) {
            let time = duration-0.2;
            if (time<0) time =0;
            this.scheduleOnce(()=>{
                EventMgr.Instance.Emit("OpenKillRoomDoor",null);
            },time);
        }
    }

    public moveOver(){
        this.playerImg.animation = this.skinName+"zhan";
        if (this.moveDir!="forward") return;
        if (this.overFun) {
            this.overFun();
        }
    }
    
}


